/*
 * @Author: cola(sunshiwen)
 * @Date: 2022-04-22 10:05:24
 * @LastEditTime: 2022-05-20 14:57:17
 * @LastEditors: cola(sunshiwen)
 * @Description: 分支管理 controller
 * @FilePath: /maycur-koa/controller/deployManageCtrl.js
 */
const { Op } = require("sequelize");
const { deployProduct, deployEnv } = require('../model/deployManageModel');
/**
 * NOTE
 * deployProduct 产品应用表
 * deployEnv 部署项目环境表
*/
module.exports = {
    fetchDeployProductList: async ctx => {
        const data = await deployProduct.findAll();
        ctx.body = data;
    },
    addNewDeployProduct: async ctx => {
        const { name, code } = ctx.reqParams.body;
        const data = await deployProduct.findOne({
            where: {
                [Op.or]: [
                    { name },
                    { code }
                ]
            }
        });
        if (data) {
            throw new Error('产品名称或编码已存在，请修改！');
        }
        await deployProduct.create({
            name,
            code,
        });
        ctx.body = 'SUCCESS';
    },
    fetchDeployEnvList: async ctx => {
        const { category } = ctx.reqParams.router;
        const data = await deployEnv.findAll({ where: { category } });
        ctx.body = data;
    },
    addNewDeployEnv: async ctx => {
        const { category, deployLink, deployName, env } = ctx.reqParams.body;
        const data = await deployEnv.findOne({
            where: {
                env,
                deployName,
                category,
            }
        });
        if (data) {
            throw new Error('该环境下已存在此项目！');
        }
        await deployEnv.create({
            category,
            deployLink,
            deployName,
            env
        });
        ctx.body = 'SUCCESS';
    },
    updateDeployEnv: async ctx => {
        const {
            category,
            deployLink,
            deployName,
            env,
            id,
        } = ctx.reqParams.body;
        const data = await deployEnv.findOne({
            where: {
                category,
                env,
                deployName,
                id: {
                    [Op.ne]: id
                }
            }
        });
        if (data) {
            throw new Error('该环境下已存在此项目！');
        }
        await deployEnv.update({ deployName, deployLink }, { where: { id, category, env } });
        ctx.body = 'SUCCESS';
    }
};